import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Card, Icon, message, Popconfirm, Table } from 'antd';
import { PageLoading } from '@ant-design/pro-layout';

import UserModal from './UserModal';

class User extends Component {

  constructor(props) {
    super(props);
    const { roles } = this.props;
    this.columns = [{
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: '20%',
    }, {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: '20%',
    }, {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
      width: '20%',
    }, {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      width: '20%',
    }, {
      title: '操作',
      key: 'operation',
      render: (record) => {
        if(record.username === 'admin') {
          return '';
        }
        return (
          <span>
            <UserModal onOk={value => this.handleEdit(record.username, value)} title='修改用户' record={record} roles={roles}>
              <a className={'table-action'}>修改</a>
            </UserModal>
            <Popconfirm title='确定要删除此用户吗?' onConfirm={() => this.handleDelete(record.username)}>
              <a className={'table-action'}>删除</a>
            </Popconfirm>
          </span>
        )
      },
      width: '20%',
    }];
  }

  reload = () => {
    this.props.dispatch({type: 'user/fetch', payload: { pageNo: 1 } });
  };

  handleAdd = (value)=>{
    return this.props.dispatch({ type: 'user/add', payload: value }).then(response => {
      if (response && typeof response.state !== undefined && response.state === 0) {
        message.success(response.message);
        this.reload();
        return response;
      } else {
        message.error('添加用户失败!');
      }
    });
  }

  handleEdit = (username, value) => {
    return this.props.dispatch({
      type: 'user/edit',
      payload: { username, rest: value },
    }).then(response => {
      if (response && typeof response.state !== undefined && response.state === 0) {
        message.success(response.message || '修改用户成功!');
        this.reload();
        return response;
      } else {
        message.error('修改用户失败!');
      }
    });
  };

  // 删除
  handleDelete = username => {
    this.props.dispatch({
      type: 'user/remove',
      payload: username,
    }).then(response => {
      if (response && typeof response.state !== undefined && response.state === 0) {
        message.success(response.message || '删除用户成功!');
        this.reload();
      } else {
        message.error('删除用户失败!');
      }
    });
  };

  handlePageChange = (changePageNo) => {
    const { pageNo, dispatch } = this.props;
    if (changePageNo !== pageNo) {
      dispatch({ type: 'user/fetch', payload: { pageNo: changePageNo } });
    }
  };

  componentDidMount() {
    this.props.dispatch({type: 'user/fetch', payload: { pageNo: 1 } });
    this.props.dispatch({type: 'user/getAllRoles'});
  }

  render() {
    const { total, list, loading, addLoading, pageSize, pageNo, roles, getAllRolesLoading } = this.props;
    if(loading || getAllRolesLoading) {
      return <PageLoading/>;
    }
    const extra = (
      <UserModal onOk={this.handleAdd} addLoading={addLoading} roles={roles}>
        <Button type='primary'>
          <Icon type='plus'/> 添加用户
        </Button>
      </UserModal>
    );
    return (
      <Card extra={extra}>
        <Table
          className={'table-wrapper'}
          columns={this.columns}
          dataSource={list}
          rowKey='_id'
          loading={loading}
          pagination={{
            total: total,
            pageSize: pageSize,
            current: pageNo,
            onChange: this.handlePageChange,
          }}
        />
      </Card>
    );
  }
}

export default connect(({ user, loading }) => ({
  ...user,
  loading: loading.effects['user/fetch'],
  addLoading: loading.effects['user/add'],
  getAllRolesLoading: loading.effects['user/getAllRoles'],
}))(User);
